<template>
  <div class="home">
    <el-input v-model="webSocketMessage"></el-input>
    <el-button @click="sendMessage(webSocketMessage)">发送消息</el-button>
    <el-button @click="closeWebSocket">关闭连接</el-button>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'HomeView',
  components: {
    HelloWorld
  },
  data () {
    return {
      webSocketMessage: "",
    }
  },
  computed: {
    websocket () {
      return this.$store.state.webSocket.ws;
    },
  },
  watch: {
    websocket (newVal) {
      if (newVal) {
        newVal.onmessage = (event) => {
          // 处理接收到的消息
          console.log('Received message:', event.data);
          this.$notify.success({
            title: '新消息',
            message: event.data,
            position: "top-right",
            duration: 3000,
            showClose: true
        });
        };
      }
    },
  },
  mounted () {
    this.$store.dispatch('startWebSocket');
  },
  methods: {
    sendMessage (message) {
      this.$store.dispatch('sendWebSocketMessage', message);
    },
    closeWebSocket(){
      this.$store.dispatch('clearWebSocket', true);
    },
  },
}
</script>
